#encoding=utf-8
import base64
import hashlib

import rsa
import yaml

from common.base_url import ini_read


class DebugTalk:

    def read_yaml(self,key):
        with open("public_param.yaml", encoding="utf-8") as f:
            value = yaml.safe_load(f)
            return value[key]

    def env(self,key):
        return ini_read()[key]

    def md5_encode(self,data):
        # 将data转化为utf-8的格式以防中文乱码
        data = str(data).encode("utf-8")
        # 使用md5加密,哈希算法
        md5_value = hashlib.md5(data).hexdigest()
        return md5_value

    def base64_encode(self,data):
        # 将data转化为utf-8的格式以防中文乱码
        data = str(data).encode("utf-8")
        # 使用md5加密,哈希算法
        base64_value = base64.b64encode(data).decode(encoding="utf-8")
        return base64_value

    #安装rsa的包,生成rsa的公钥和私钥
    def create_rsa_key(self):
        (public_key,private_key) = rsa.newkeys(1024)
        with open("./ public_key.pem","w+") as f:
            f.write(public_key.save_pkcs1().decode())
        with open("./private_key.pem", "w+") as f:
            f.write(private_key.save_pkcs1().decode())

    def rsa_encode(self,data):
        # 加载公钥
        with open("./hotload/public_key.pem", "r") as f:
            pubkey = rsa.PublicKey.load_pkcs1(f.read().encode())
        # 把data转化为utf-8的格式
        data = str(data).encode("utf-8")
        # 把字符加密为byte类型
        byte_value = rsa.encrypt(data,pubkey)
        # 把字节转化为字符串格式
        rsa_value = base64.b64encode(byte_value).decode(encoding="utf-8")
        return rsa_value


if __name__ == '__main__':
    print(DebugTalk().md5_encode("admin"))
    print(DebugTalk().base64_encode("admin"))
    DebugTalk().create_rsa_key()

